package uk.co.droidinactu.sony.prst1.home.view;

import uk.co.droidinactu.sony.prst1.home.R;
import uk.co.droidinactu.sony.prst1.home.data.Collection;
import uk.co.droidinactu.sony.prst1.home.data.DataModel;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public final class CollectionsActivity extends AbstractListActivity implements OnItemClickListener {

	private static final int[] collctnColsMapTo = new int[] { R.id.collection_list_item_title,
			R.id.collection_list_item_count };

	private static final String[] collctnColumns = new String[] { Collection.COLUMN_NAME_TITLE,
			Collection.COLUMN_NAME_UUID };

	private DataModel dataModel;
	private ListView listView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.collection_list);
		listView = (ListView) findViewById(R.id.collection_list);
		listView.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
		final Intent incdntDetailsIntnt = new Intent(this, BooksActivity.class);
		incdntDetailsIntnt.putExtra(BooksActivity.SELECTED_COLLECTION_ID, id);
		startActivity(incdntDetailsIntnt);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (dataModel == null) {
			dataModel = new DataModel(this);
		}
		updateList();
	}

	private void updateList() {
		Cursor cursr = dataModel.getCollections(this);
		final SimpleCursorAdapter tmpAdaptor = new SimpleCursorAdapter(this, R.layout.collection_list_item,
				cursr, collctnColumns, collctnColsMapTo);
		tmpAdaptor.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			@Override
			public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
				boolean retval = false;
				final int idColIndex = cursor.getColumnIndexOrThrow(Collection.COLUMN_NAME_UUID);
				final int titleColIndex = cursor.getColumnIndexOrThrow(Collection.COLUMN_NAME_TITLE);

				if (columnIndex == idColIndex) {
					try {
						final TextView txtbookCount = (TextView) view;
						final String collcnName = cursor.getString(titleColIndex);
						Cursor crsr = dataModel.getBooksInCollection(CollectionsActivity.this, collcnName);
						int bookCount = crsr.getCount();
						crsr.close();
						txtbookCount.setText("(" + bookCount + ")");
						retval = true;
					} catch (final Exception e) {
					}
					retval = true;
				}
				return retval;
			}
		});
		listView.setAdapter(tmpAdaptor);
		tmpAdaptor.notifyDataSetChanged();
	}
}
